package me.firstapp.bbs.controller;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import me.firstapp.bbs.base.BaseController;
import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.bbs.JsonMember;
import me.firstapp.common.module.shop.TempshoppingCart;
import me.firstapp.common.module.shop.TempshoppingCartItem;
import me.firstapp.common.utils.CookieUtils;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.spi.bbs.CollectionService;
import me.firstapp.spi.bbs.EmailService;
import me.firstapp.spi.bbs.MemberService;
import me.firstapp.spi.shop.ShoppingCartService;

@Controller
@RequestMapping(value = "/member")
public class MemberController extends BaseController {

	@Autowired
	private MemberService memberService;

	@Autowired
	private ShoppingCartService shoppingCartService;

	@Autowired
	private CollectionService collectionService;

	@Autowired
	private EmailService emailService;

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView registerView(String returnUrl, HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		if (returnUrl.contains("member/login") || returnUrl.contains("member/register")) {
			returnUrl = request.getContextPath();
		}
		modelMap.put("returnUrl", returnUrl);
		return new ModelAndView("member/register", modelMap);
	}

	@RequestMapping(value = "/register.do", method = RequestMethod.POST)
	public void register(String email, String name, String password, String code, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributesModelMap modelMap) {
		SingleObject<Object> result = new SingleObject<>();
		JsonMember jsonMember = null;
		try {
			SingleObject<JsonMember> _result = memberService.register(email, name, password, code);
			if (StatusHouse.COMMON_STATUS_OK.getCode().equals(_result.getCode())) {
				jsonMember = _result.getObject();
				String loginToken = StrUtils.getLoginToken();
				setCookieLoginToken(response, loginToken);
				redisTemplate.opsForValue().set("login_member_" + loginToken, jsonMember);
				redisTemplate.expire("login_member_" + loginToken, 30, TimeUnit.MINUTES);
			} else {
				throw new ServiceException(_result.getCode(), _result.getMsg());
			}
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}

		ResponseUtils.renderJson(response, result);

		// 更新购物车
		TempshoppingCart tempShoppingCart = (TempshoppingCart) request.getSession().getAttribute("shoppingCart");
		if (tempShoppingCart != null && jsonMember != null) {
			updateShoppingCart(jsonMember, tempShoppingCart);
		}
		if (jsonMember != null) {
			emailService.sendEmail(email, "注册成功通知", "恭喜你注册成功。【FirstApp.Me】");
		}
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView loginView(String returnUrl, HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		if (StrUtils.isNotNULL(returnUrl)) {
			if (returnUrl.contains("member/login") || returnUrl.contains("member/register")) {
				returnUrl = request.getContextPath();
			}
			modelMap.put("returnUrl", returnUrl);
		}
		return new ModelAndView("member/login", modelMap);
	}

	@RequestMapping(value = "/forgotPassword", method = RequestMethod.GET)
	public ModelAndView forgotPasswordView(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		return new ModelAndView("member/forgotPassword", modelMap);
	}

	@RequestMapping(value = "/resetPassword.do", method = RequestMethod.POST)
	public void resetPassword(String email, String password, String code, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		SingleObject<Object> result = memberService.resetPassword(email, code, password);
		if (StatusHouse.COMMON_STATUS_OK.getCode().equals(result.getCode())) {
			String loginToken = getCurrentLoginToken(request, response);
			redisTemplate.opsForValue().set("login_member_" + loginToken, null);
			CookieUtils.clearCookieByName(request, response, "loginToken");
			request.getSession().removeAttribute("shoppingCart");
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public ModelAndView logout(String account, String password, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		String loginToken = getCurrentLoginToken(request, response);
		redisTemplate.opsForValue().set("login_member_" + loginToken, null);
		CookieUtils.clearCookieByName(request, response, "loginToken");
		request.getSession().removeAttribute("shoppingCart");
		return new ModelAndView("redirect:/", modelMap);
	}

	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public void login(String account, String password, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<JsonMember> result = memberService.login(account, password);
		if (!StatusHouse.COMMON_STATUS_OK.getCode().equals(result.getCode())) {
			ResponseUtils.renderJson(response, result);
			return;
		}
		JsonMember jsonMember = result.getObject();
		if (jsonMember != null) {
			String loginToken = StrUtils.getLoginToken();
			setCookieLoginToken(response, loginToken);
			redisTemplate.opsForValue().set("login_member_" + loginToken, jsonMember);
			redisTemplate.expire("login_member_" + loginToken, 30, TimeUnit.MINUTES);
		}
		ResponseUtils.renderJson(response, result);
		// 更新购物车
		TempshoppingCart tempShoppingCart = (TempshoppingCart) request.getSession().getAttribute("shoppingCart");
		if (tempShoppingCart != null) {
			updateShoppingCart(jsonMember, tempShoppingCart);
		}
	}

	@RequestMapping(value = "/changCollectionStatus.do", method = RequestMethod.POST)
	public void changCollectionStatus(Long topicId, Long productId, Integer type, Boolean isCollection,
			HttpServletRequest request, HttpServletResponse response) {
		JsonMember member = getCurrentLoginMember(request, response);
		SingleObject<Boolean> result = collectionService.changCollectionStatus(member.getId(), topicId, productId, type,
				isCollection);
		ResponseUtils.renderJson(response, result);
	}

	private void updateShoppingCart(JsonMember jsonMember, TempshoppingCart tempShoppingCart) {
		List<TempshoppingCartItem> items = tempShoppingCart.getItems();
		JSONArray jsonArray = new JSONArray();
		if (items != null) {
			for (TempshoppingCartItem tempshoppingCartItem : items) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("productId", tempshoppingCartItem.getProductId());
				jsonObject.put("productSkuRelId", tempshoppingCartItem.getProductSkuRelId());
				jsonObject.put("counts", tempshoppingCartItem.getCounts());
				jsonArray.add(jsonObject);
			}
		}
		String params = JSONArray.toJSONString(jsonArray);
		shoppingCartService.updateShoppingCart(jsonMember.getShoppingCart().getId(), params);
	}

}
